package com.app.controller;

import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.app.mapper.EnjoyMapper;
import com.app.model.*;
import com.app.service.*;
import com.app.util.CommonHelp;
import com.app.util.Result;
import com.app.util.TokenUtils;
import com.app.vo.CategoryVo;
import com.app.vo.EnjoyVo;
import com.app.vo.PersonVo;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import freemarker.core.ReturnInstruction;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.thymeleaf.util.ListUtils;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@Controller
@RequestMapping("/api/enjoy")
public class EnjoyController {
    @Autowired
    private CategoryService categoryService;
    @Autowired
    private EnjoyService enjoyService;
    @Autowired
    private PersonService personService;
    @Autowired
    private AdminUserService adminUserService;
    @Autowired
    private DepartmentService departmentService;
    @Autowired
    private EnjoyMapper enjoyMapper;

    //福利类型列表
    @GetMapping("/enjoyTypeList")
    public Result<Object> enjoyTypeList(HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        CategoryVo vo = new CategoryVo();
        List<CategoryModel> enjoyType = categoryService.getCategoryByPid(98);
        vo.setTypeList(enjoyType);
        List<PersonModel> personName = personService.getPersonName();
        vo.setPersonList(personName);
        return Result.success(vo);
    }

    //新增和编辑
    @PostMapping("/insertEnjoy")
    public Result<Object> addAndUpdate(@RequestBody EnjoyModel enjoyModel, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        QueryWrapper<EnjoyModel> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("person_id", enjoyModel.getPersonId());
        EnjoyModel enjoyModel1 = enjoyMapper.selectOne(queryWrapper);
        if (enjoyModel1 != null) {
            enjoyModel.setId(enjoyModel1.getId());
            enjoyModel.setUpdateTime(CommonHelp.getNowTimestamp());
            enjoyMapper.updateById(enjoyModel);
            return Result.success("更新成功");
        } else {
            enjoyModel.setCreateTime(CommonHelp.getNowTimestamp());
            enjoyMapper.insert(enjoyModel);
            return Result.success("添加成功");
        }
    }


    //删除
    @GetMapping("/deleteEnjoyById")
    public Result<Object> deleteEnjoyById(Integer id, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        enjoyService.deleteById(id);
        return Result.success("操作成功");
    }


//    福利类型的批量删除
    @DeleteMapping("/deleteEnjoyBatchIds")
    public Result<Object> deleteEnjoyByIds(@RequestParam("ids") String ids, HttpServletRequest request) {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }
        //上面token校验


        if (StringUtils.isEmpty(ids)) {
            return Result.success(null);
        }
        List<Integer> idsList = Arrays.stream(ids.split(","))
                .map(Integer::valueOf)
                .collect(Collectors.toList());
        if (ListUtils.isEmpty(idsList)) {
            return Result.success(null);
        }
        enjoyMapper.deleteBatchIds(idsList);
        return Result.success(null);
    }


    //列表展示
    @GetMapping("/getEnjoyList")
    public Result<Object> selectEnjoyList(
            @RequestParam("page") Integer page,
            @RequestParam("limit") Integer limit,
            @RequestParam("name") String name,
            Integer year,
            HttpServletRequest request) throws JsonProcessingException {
        String token = request.getHeader("authori-zation");
        if (token == null) {
            return Result.error(405, "token不存在");
        }
        String userId = TokenUtils.verify(token);
        AdminUserModel user = adminUserService.getUserByUserId(Integer.parseInt(userId));
        if (user == null) {
            return Result.error(406, "用户不存在");
        }

        List<Integer> idList = departmentService.getDepId(user.getDepartmentId());
        Page<PersonModel> getPageEnjoyList = personService.getPageEnjoyList(page, limit, name, idList);
        for (int i = 0; i < getPageEnjoyList.getRecords().size(); i++) {
            QueryWrapper<EnjoyModel> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("person_id", getPageEnjoyList.getRecords().get(i).getId());
            EnjoyModel enjoyModel = enjoyMapper.selectOne(queryWrapper);
            if (enjoyModel != null) {
                getPageEnjoyList.getRecords().get(i).setSeparation(enjoyModel.getSeparation());
                getPageEnjoyList.getRecords().get(i).setEducationFee(enjoyModel.getEducationFee());
                getPageEnjoyList.getRecords().get(i).setNoEmploy(enjoyModel.getNoEmploy());
                getPageEnjoyList.getRecords().get(i).setProvide(enjoyModel.getProvide());
                getPageEnjoyList.getRecords().get(i).setSupportAllowance(enjoyModel.getSupportAllowance());
                getPageEnjoyList.getRecords().get(i).setComfort(enjoyModel.getComfort());
                getPageEnjoyList.getRecords().get(i).setNotArmy(enjoyModel.getNotArmy());
            } else {
                getPageEnjoyList.getRecords().get(i).setSeparation("");
                getPageEnjoyList.getRecords().get(i).setEducationFee("");
                getPageEnjoyList.getRecords().get(i).setNoEmploy("");
                getPageEnjoyList.getRecords().get(i).setProvide("");
                getPageEnjoyList.getRecords().get(i).setSupportAllowance("");
                getPageEnjoyList.getRecords().get(i).setComfort("");
                getPageEnjoyList.getRecords().get(i).setNotArmy("");
            }
        }
        int count = (int) getPageEnjoyList.getTotal();
        List<PersonModel> enjoyModelList;
        enjoyModelList = getPageEnjoyList.getRecords();
        PersonVo vo = new PersonVo();
        vo.setList(enjoyModelList);
        vo.setCount(count);
        return Result.success(vo);
    }
}
